<?php
define('IN_QY',true);
session_start();
require("include/common.inc.php");
require_once('config.php');
$code = $_GET['code'];
$state = $_GET['state'];
//换成自己的接口信息
$appid = 'wxd6671ed64906b4b4';
$appsecret = '04b2aa5188bde40a5adecb5fbaea226a';
if (empty($code)) $this->error('授权失败');
$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
$token = json_decode(file_get_contents($token_url));
if (isset($token->errcode)) {
    echo "<script type='text/javascript'>location.href='wxzflogin.php';</script>";
    exit;
}
$access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
//转成对象
$access_token = json_decode(file_get_contents($access_token_url));
if (isset($access_token->errcode)) {
    echo "<script type='text/javascript'>location.href='wxzflogin.php';</script>";
    exit;
}
$user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
//转成对象
$user_info = json_decode(file_get_contents($user_info_url),true);


$sqlu = "select * from tbl_user where wxopenid='".$user_info['unionid']."'";
$queryu=mysql_query($sqlu);
$rowu=mysql_fetch_array($queryu);

if($rowu){
echo "<script type='text/javascript'>alert('当前微信已绑定其他账号');location.href='my.php';</script>";
	exit;
}


        $sql = "update tbl_user set wxopenid='".$user_info['unionid']."' where id='".$_COOKIE['userid']."'";
        mysql_query($sql);



setcookie("wxheadimgurl",$user_info['headimgurl'],time()+(3600*12*1*1));
setcookie("wxnickname",$user_info['nickname'],time()+(3600*12*1*1));
setcookie("wxopenid",$user_info['unionid'],time()+(3600*12*1*1));
echo "<script type='text/javascript'>alert('绑定成功');location.href='my.php';</script>";
?>
